<?php

class RestController extends Zend_Controller_Action
{
    public function init()
    {
        //require 'Indexer/Searchable.php';
        //require 'Indexer/Service.php';
        $this->logger = Indexer_Service::getLog();
        parent::init();
    }
    
    public function indexAction()
    {
        $this->logger->debug('Entering '.__METHOD__);
        echo "This is a REST interface for Zend_Search_Lucene";
    }
    
	public function serviceAction()
	{
	    $this->logger->debug('Entering '.__METHOD__);
	    
	    $paramWhileList = array('documentObject', 'path', 'phrase', 'method', 'documentList');
	    $checkParams = $this->_getAllParams();
	    $this->logger->debug('Received request to: '.$_SERVER['REQUEST_URI']);
	    //$this->logger->debug('Request params: ' . print_r($checkParams,true));
	    $params = array();
	    foreach($checkParams as $name => $value) {
	        if (in_array($name, $paramWhileList)) {
	            $params[$name] = $value;
	        }
	    }
	    if (isset($params['phrase'])) {
	        $params['method'] = 'search';
	    }
	    $args = array();
	    if (!empty($checkParams['catalog'])) {
	        $args['catalog'] = $checkParams['catalog'];
	    }
	    $rest = new Zend_Rest_Server();
	    $this->logger->debug('Calling Marjory service class with constructor args: '.print_r($args,true));
        $rest->setClass('Indexer_Service', '', $args);
        //$this->logger->debug('Invoking REST service with params: '.print_r($params,true));
	    $rest->handle($params);
	}
	
	/**
	 * Supposed to behave mostly similar to Solr's select action
	 */
	public function selectAction()
	{
	    $this->logger->debug('Entering '.__METHOD__);
	    $paramWhiteList = array('q', 'wt', 'fl', 'rows', 'start');
        $checkParams = $this->_getAllParams();
        $this->logger->debug('Received request to: '.$_SERVER['REQUEST_URI']);
        //$this->logger->debug('Request params: ' . print_r($checkParams,true));
        /**
         * Unfortunately, Zend_Rest_Server does not deal with optional parameters, 
         * so we have to set default values explicitly:
         */
        $params = array('wt' => false, 'fl' => false, 'rows' => 0, 'start' => 0);
        $this->logger->debug('Foreach now...');
        foreach($checkParams as $name => $value) {
            $this->logger->debug('In foreach...');
            if (in_array($name, $paramWhiteList)) {
                $this->logger->debug('Adding to params: '.$name);
                $params[$name] = $value;
            } else {
                $this->logger->debug('Check failed for: '.$name);
            }
        }
        $params['method'] = 'search'; // make sure Rest_Server calls search method
        
        /* @TODO add possibility to ignore catalog param and set catalog by hostname instead */
	    $args = array();
        if (!empty($checkParams['catalog'])) {
            $args['catalog'] = $checkParams['catalog'];
        }
        
        $rest = new Zend_Rest_Server();
        $this->logger->debug('Calling Marjory service class with constructor args: '.print_r($args,true));
        $rest->setClass('Indexer_Service', '', $args);
        //$this->logger->debug('Invoking REST service with params: '.print_r($params,true));
        $rest->handle($params);
        
	}
	
	/**
     * Supposed to behave mostly similar to Solr's update action
     */
	public function updateAction()
	{
        $this->logger->debug('Entering '.__METHOD__);
        $rest                     = new Zend_Rest_Server();
        $args                     = array();
        $params                   = array();
        $params['documentObject'] = array();
        $method                   = null;
        
        // try to parse raw post data as XML
        try {
            $xml = simplexml_load_file('php://input');
        } catch(Exception $ex) {
            return $rest->fault(new Exception('Error when parsing message: '.$ex->getMessage(), $ex->getCode()));
        }
        
        /* @TODO add possibility to ignore catalog param and set catalog by hostname instead */
        if (!empty($xml['catalog'])) {
            $args['catalog'] = (string)$xml['catalog'];
        }
        
        switch($xml->getName()) {
            case 'add':
                //$method = 'addDocument';
                /* @TODO Implement other engine backends and see how adding is best handled for engines that differentiate between add and update */
                
                /*
                <add>
                  <doc>
                    <field name="id">9885A004</field>
                    <field name="name">Canon PowerShot SD500</field>
                    <field name="category">camera</field>
                    <field name="features">3x optical zoom</field>
                    <field name="features">aluminum case</field>
                    <field name="weight">6.4</field>
                    <field name="price">329.95</field>
                  </doc>
                </add>
                */
                
            case 'update':
                if (empty($method)) {
                    $method = 'updateDocument';
                }
                $params['documentList'] = $xml->xpath('//doc');
                
                break;
            case 'delete':
                /*
                <delete><uri>05991</uri></delete>
                <delete><query>office:Bridgewater</query></delete>
                */
                $method = 'removeDocument';
                /* @TODO Implement delete by query */
                $params['documentList'] = $xml->xpath('//uri');
                break;
        }
        $params['method'] = $method;
        $this->logger->debug('Calling Marjory service class with constructor args: '.print_r($args,true));
        $rest->setClass('Indexer_Service', '', $args);
        //$this->logger->debug('Invoking REST service with params: '.print_r($params,true));
        $rest->handle($params);
	}
	
	public function catalogAction()
	{
	    $this->logger->debug('Entering '.__METHOD__);
        $rest                     = new Zend_Rest_Server();
        $args                     = array();
        $params                   = array();
	    
	    // try to parse raw post data as XML
        try {
            $xml = simplexml_load_file('php://input');
        } catch(Exception $ex) {
            return $rest->fault(new Exception('Error when parsing message: '.$ex->getMessage(), $ex->getCode()));
        }

        $params['catalog'] = (string)$xml['catalog'];
        $params['method'] = 'createNewIndex'; // make sure Rest_Server calls createNewIndex method
        
        $args['catalog'] = (string)$xml['catalog'];
        
        $this->logger->debug('Calling Marjory service class with constructor args: '.print_r($args,true));
        $rest->setClass('Indexer_Service', '', $args);
        //$this->logger->debug('Invoking REST service with params: '.print_r($params,true));
        $rest->handle($params);	    
	}
	
	public function __call($method, $params)
	{
	    $this->_response->setHttpResponseCode(404);
	    echo "<html><head><title>404: Not found</title></head><body><h1>Error 404</h1><p>The URL you entered was not found at this server.</p></body></html>";	    
	}
}
